package com.flyee.utils.textload.control
{
	import com.flyee.utils.textload.model.TextLoaderModel;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class TextLoaderManager
	{
		private static var instance:TextLoaderManager = null;
		
		private var loaderList:Array = new Array();
		private var isOpen:Boolean = true;
		private var loadingLoader:TextLoaderModel = null;
		public function TextLoaderManager()
		{
			if (instance)
			{
				throw new Error("singleton error!!!");
			}
			instance = this;
		}
		public static function getInstance():TextLoaderManager
		{

			if (instance == null)
			{
				instance = new TextLoaderManager();
			}
			return instance;
		}
		public function regist(loader:TextLoaderModel):void
		{
			loaderList.push(loader);
			this.startLoad();
		}
		private function startLoad():void
		{
			if(isOpen)
			{
				if(this.loaderList.length > 0)
				{
					this.isOpen = false;
					loadingLoader = this.loaderList.shift() as TextLoaderModel;
					loadingLoader.load(new URLRequest(loadingLoader.loadURL));
					loadingLoader.addEventListener(Event.COMPLETE,completeHandle);
					loadingLoader.addEventListener(ProgressEvent.PROGRESS,progressHandle);
					loadingLoader.addEventListener(IOErrorEvent.IO_ERROR,errorHandle);
				}
			}
		}
		private function completeHandle(e:Event):void
		{
			if(loadingLoader)
			{
				loadingLoader.removeEventListener(Event.COMPLETE,completeHandle);
				loadingLoader.removeEventListener(ProgressEvent.PROGRESS,progressHandle);
				loadingLoader.removeEventListener(IOErrorEvent.IO_ERROR,errorHandle);
				if(loadingLoader.returnFun != null)
				{	
					loadingLoader.returnFun(loadingLoader.data);
				}
			}
			loadingLoader = null;
			this.isOpen = true;
			startLoad();
		}
		private function progressHandle(e:ProgressEvent):void
		{
			if(loadingLoader)
			{
				if(loadingLoader.progressFun != null)
				{
					loadingLoader.progressFun(e.bytesLoaded,e.bytesTotal);
				}
			}
		}
		private function errorHandle(e:IOErrorEvent):void
		{
			this.isOpen = true;
			if(loadingLoader)
			{
				loadingLoader.removeEventListener(Event.COMPLETE,completeHandle);
				loadingLoader.removeEventListener(ProgressEvent.PROGRESS,progressHandle);
				loadingLoader.removeEventListener(IOErrorEvent.IO_ERROR,errorHandle);
				if(loadingLoader.ioErrorFun != null)
				{
					loadingLoader.ioErrorFun(e.text);
				}
			}
			loadingLoader = null;
			startLoad();
		}
	}
}